package com.hs.auth.controller;

import com.hs.auth.form.LoginBody;
import com.hs.auth.form.RegisterBody;
import com.hs.auth.service.impl.LoginServiceImpl;
import com.hs.common.core.domain.Result;
import com.hs.common.core.utils.JwtUtils;
import com.hs.common.core.utils.StringUtils;
import com.hs.common.core.web.domain.AjaxResult;
import com.hs.common.security.auth.AuthUtil;
import com.hs.common.security.service.TokenService;
import com.hs.common.security.utils.SecurityUtils;
import com.hs.system.api.model.LoginUser;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * token 控制
 */
@RestController
@RequestMapping("/auth")
public class TokenController {
    @Resource
    private TokenService tokenService;

    @Resource
    private LoginServiceImpl loginService;

    @PostMapping("/login")
    public Result<?> login(@RequestBody LoginBody form) {
        System.out.println("用户登录 login 方法form=" + form);
        // 用户登录
        LoginUser userInfo = loginService.login(form.getEmail(), form.getPassword());
        // 获取登录token
        return Result.ok(tokenService.createToken(userInfo));
    }

    @DeleteMapping("/logout")
    public Result<?> logout(HttpServletRequest request) {
        String token = SecurityUtils.getToken(request);
        String msg = null;
        if (StringUtils.isNotEmpty(token)) {
            String username = JwtUtils.getUserName(token);
            // 删除用户缓存记录
            AuthUtil.logoutByToken(token);
            // 记录用户退出日志
            msg = loginService.logout(username);
        }
        return Result.ok(msg);
    }

    @PostMapping("/refresh")
    public Result<?> refresh(HttpServletRequest request) {
        System.out.println("刷新方法");
        LoginUser loginUser = tokenService.getLoginUser(request);
        if (StringUtils.isNotNull(loginUser)) {
            // 刷新令牌有效期
            String msg = tokenService.refreshToken(loginUser);
            return Result.ok(msg);
        }
        return Result.ok();
    }

    @PostMapping("/register")
    public Result<?> register(@RequestBody RegisterBody registerBody) {
        System.out.println("auth里面的注册方法");
        // 用户注册
        String msg = loginService.register(registerBody);
        return Result.ok(msg);
    }

    /**
     * 注册页面获取邮箱验证码,通过邮箱发送验证码
     *
     * @param
     * @return
     */
    @GetMapping("/code/email")
    public AjaxResult getCodeEmil(String email) {
        System.out.println("getCodeEmil 方法email=" + email);
        return loginService.getCodeEmail(email);
    }
}
